package com.kakaxi.mybilibili.module.video.model;

import android.content.Context;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kakaxi.mybilibili.common.AppConst;
import com.kakaxi.mybilibili.common.WebUrlConst;
import com.kakaxi.mybilibili.net.FastJsonCacheRequest;
import com.kakaxi.mybilibili.net.Netroid;
import com.kakaxi.mybilibili.net.StringCacheRequest;
import com.kakaxi.mybilibili.utils.EscapeUtil;
import com.kakaxi.mybilibili.utils.LogUtil;
import com.kakaxi.mybilibili.utils.URLUtil;
import com.vincestyling.netroid.Listener;
import com.vincestyling.netroid.NetroidError;
import com.vincestyling.netroid.request.StringRequest;

import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import static com.kakaxi.mybilibili.common.WebUrlConst.VIDEO_WEBVIEW_FRONT_URL;

/**
 * 视频数据层实现类
 * Created by kakaxi on 16/11/20.
 * <p>
 * http://api.bilibili.com/archive_stat/stat?aid=7139116
 * http://api.bilibili.com/view?type=json&appkey=8e9fc618fbd41e28&id=7186025
 * http://interface.bilibili.com/playurl?cid=11723684&otype=json&player=1&quality=3&type=mp4&sign
 * =8bc3a21b5c841d36d1e19367d69534ce
 */

public class VideoModel implements IVideoModel {

    private WebView mWebView;

    /** 是否已经获取视频网址 **/
    private boolean mHasGetVideoUrl;

    /** 获取视频的真实的网址 **/
    private String mRealVideoUrl;

    @Override
    public void initVideo(Context context) {
        mWebView = new WebView(context);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setAppCacheEnabled(true);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
    }

    @Override
    public void getVideoDataFromWebView(String aid, final Listener<String> listener) {
        mHasGetVideoUrl = false;
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (mHasGetVideoUrl) {
                    getVideoDataFromPlayUrl(listener);
                } else {
                    listener.onError(new NetroidError("获取视频失败,请重试"));
                }
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                if (url.startsWith(WebUrlConst.VIDEO_WEBVIEW_REAL_FRONT_URL)) {
                    mHasGetVideoUrl = true;
                    mRealVideoUrl = url;
                }
                return super.shouldInterceptRequest(view, url);
            }

        });
        mWebView.loadUrl(VIDEO_WEBVIEW_FRONT_URL + aid + "/");
    }

    /***
     * 从webview拦截的视频请求获取视频的播放网址
     *
     * @param listener 回调
     *
     */
    private void getVideoDataFromPlayUrl(final Listener<String> listener) {
        Netroid.addRequest(new StringCacheRequest(mRealVideoUrl, null, new Listener<String>() {
            @Override
            public void onSuccess(String response) {
                super.onSuccess(response);
                try {
                    // 取出json那一部分数据
                    response = response.substring(response.indexOf("{"), response.lastIndexOf(")"));
                    LogUtil.d("视频json截取结果:" + response);
                    JSONObject responseJsonObj = JSON.parseObject(response);
                    String result = responseJsonObj.getString("result");
                    if (result != null && result.equals("suee")) {
                        String videoUrl = responseJsonObj.getJSONArray("durl").getJSONObject(0).getString
                                ("url");
                        listener.onSuccess(videoUrl);
                        return;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                listener.onError(new NetroidError("获取视频失败,请重试"));
            }

            @Override
            public void onError(NetroidError error) {
                super.onError(error);
                listener.onError(new NetroidError("获取视频失败,请重试"));
            }
        }), true);
    }

    public void getVideoDataFromBilijj(String cid, final Listener<String> listener) {
        String url = WebUrlConst.VIDEO_BILIJJ_DOWNLOAD_URL + cid;
        Netroid.addRequest(new StringRequest(url, listener), true);
    }


    @Override
    public void getVideoIntroData(String aid, Listener<JSONObject> listener) {
        String url = WebUrlConst.VIDEO_INTRO_URL + aid;
        Netroid.addRequest(new FastJsonCacheRequest(url, null, listener, null), true);
    }

    @Override
    public void getVideoData(int cid, Listener<JSONObject> listener) {
        // 构造请求参数
        SortedMap<String, String> paramMap = new TreeMap<>();
        paramMap.put("appkey", "84956560bc028eb7");
        paramMap.put("cid", String.valueOf(cid));
        paramMap.put("otype", "json");
        paramMap.put("player", "1");
        paramMap.put("quality", "3");
        paramMap.put("type", "flv");
        String params = URLUtil.getParamString(paramMap);
        // 通过参数计算出sign
        String signValue = EscapeUtil.md5(params + AppConst.WEB_API_ACCESS);

        LogUtil.d("params=" + params + " sign=" + signValue);

        // 组装最终的请求链接
        String url = WebUrlConst.VIDEO_URL + "?" + params + "&sign=" + signValue;

        // 创建请求并设置请求标头
        FastJsonCacheRequest request = new FastJsonCacheRequest(url, null, listener, null);
//        request.addHeader("Accept", "application/json, text/javascript, */*; q=0.01");
//        request.addHeader("Accept-Encoding", "gzip, deflate, sdch");
//        request.addHeader("Accept-Language", "zh-CN,zh;q=0.8");
//        request.addHeader("Cache-Control", "max-age=0");
//        request.addHeader("Connection", "keep-alive");
//        request.addHeader("Cookie", "fts=1479652143;pgv_pvi=8159570944;" +
//                "buvid3=C39E067C-F4E6-4E26-B9B9-373668ED5F0A28576infoc;" +
//                "BDTUJIAID=79b7736d3f1e4eb17219f6ae461fe9d2;_ga=GA1.2.1838731665.1479652162;" +
//                "pgv_si=s487932928;sid=cnm60vfv");
//        request.addHeader("Host", "interface.bilibili.com");
//        request.addHeader("Origin", "http://www.bilibili.com");
//        request.addHeader("Referer", "http://www.bilibili.com/video/av" + mAid + "/?tg");
//        request.addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) " +
//                "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36");

        // 发送请求
        Netroid.addRequest(request, true);
    }

    @Override
    public void getVideoCommentData(String aid, int pn, boolean more, Listener<JSONObject>
            listener) {
        String pnStr = String.valueOf(pn);
        // 初始化请求参数
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("oid", aid);
        paramMap.put("pn", pnStr);
        paramMap.put("ps", "20");
        paramMap.put("type", "1");
        if (more) {
            paramMap.put("sort", "2");
            paramMap.put("nohot", "1");
        } else {
            paramMap.put("sort", "0");
        }
        // 把请求参数集合转化为字符串
        String urlWithParam = URLUtil.getURLWithParam(WebUrlConst.VIDEO_COMMENT_URL, paramMap);
        Netroid.addRequest(new FastJsonCacheRequest(urlWithParam, null, listener, pnStr));
    }


    //    @Override
//    public void getVideoData(final Listener<VideoBean> listener) {
//        AsyncTask asyncTask = new AsyncTask<Object, Void, VideoBean>() {
//            @Override
//            protected VideoBean doInBackground(Object... params) {
//                Document doc;
//                try {
//                    doc = Jsoup.connect(WebUrlConst.videoHtmlUrl).userAgent("Mozilla/5.0 " +
//                            "(Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/601.7.7 (KHTML,
// like" +
//                            " Gecko) Version/9.1.2 Safari/601.7.7").get();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                    return null;
//                }
//
//                if (doc == null) {
//                    return null;
//                }
//
//                VideoBean videoBean = doInfo(doc);
//                return videoBean;
//            }
//
//            @Override
//            protected void onPostExecute(VideoBean videoBean) {
//                super.onPostExecute(videoBean);
//                if (videoBean == null) {
//                    listener.onError(new NetroidError("出错原因:链接出错!"));
//                } else {
//                    listener.onSuccess(videoBean);
//                }
//            }
//        };
//        asyncTask.execute();
//    }

//    private VideoBean doInfo(Document doc) {
//        VideoBean videoBean = new VideoBean();
//        // 标题
//        String title = doc.select("div.v-title > h1").text();
//        LogUtil.d("标题:" + title);
//        // 播放量
//        String playNum = doc.select("div.sign").text();
//        String upFace = doc.select("div.u-face img").attr("data-fn-src");
//        String upName = doc.select("a.name").text();
//        String startDate = doc.select("time i").text();
//        LogUtil.d("播放量:" + startDate);
//        return null;
//    }

}
